<?php

namespace App\Task;

use AlibabaCloud\Vcs\V20200515\VcsApiResolver;
use App\Model\DataBackhaulSetting;
use App\Model\DataPaymentBackhaul;
use App\Model\DataSpread;
use App\Model\PlayletBind;
use App\Model\Payment;
use App\Model\SystemOrderDay;
use App\Model\SystemOrderDayCount;
use GuzzleHttp\Client;
use Hyperf\Crontab\Annotation\Crontab;
use Hyperf\DbConnection\Db;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Utils\ApplicationContext;
use Psr\Log\LoggerInterface;

class DayUpdatePaymentTask
{
    protected LoggerInterface $logger;
    public function __construct(protected LoggerFactory $loggerFactory)
    {
        $this->logger = $this->loggerFactory->get('log', 'UploadOrder');
    }

    public function execute()
    {
        $container = ApplicationContext::getContainer();
        $redis = $container->get(\Hyperf\Redis\RedisFactory::class)->get('default');
        $this->logger->info(date('Y-m-d H:i:s') . '------------------------获取一段时间内的所有订单数据');
        $startUserDate = date('Y-m-d 00:00:00',time());
        $endDUserate = date("Y-m-d 23:59:59",time());
        $time = date('Y-m-d',time());
        $startDate = date('Y-m-d H:00:00',time()-3600);
        $endDate = date("Y-m-d H:59:59",time());

        $this->logger->info('开始时间为：'.$startDate);
        $this->logger->info('结束时间为：'.$endDate);
        try {
            $orderKey =  'update_today_payment_live_locah';
            $keyData = $redis->get($orderKey);
            if(!empty($keyData)){
//                $redis->del($orderKey);
                $this->logger->info('存在处理中的订单进程');
                $this->logger->info(date('Y-m-d H:i:s') . '------------------------结束定时获取订单进行上报');
                return;
            }else{
                $redis->set($orderKey,1);
            }
            $select_payment_id = 0;
            $payKey =  'upload_payment_idsssss';
            $getpaykey = $redis->get($payKey);
            if(!empty($getpaykey)){
                $select_payment_id = $getpaykey;
            }

            //判断这个订单是否处理过
            $paymentIDKey = 'payment_list_ALL_'.$time;


            //获取需要处理的订单
            $paymentData = Payment::query()
                ->select(['id','user_id','applet_id','spread_id','pay_time','status'])
//                ->where('id','>',$select_payment_id)
                ->where('pay_time','>=',$startUserDate)
                ->where('pay_time','<=',$endDUserate)
                ->where('first_recharge','Y')
                ->where('today_first_recharge','N')
                ->where('today_after_recharge','N')
                ->orderBy('pay_time','asc')
//                ->limit(100)
                ->get();

            if($paymentData->isNotEmpty()) {
                //判断是否
                $this->logger->info('订单的数据为数量为：', [count($paymentData)]);
                $date_Arr = [];
                foreach ($paymentData as $paymentDatum) {
                    $this->logger->info('判断redis中是否有这个Key：', [count($paymentData)]);
                    $result = $redis->sIsMember($paymentIDKey,$paymentDatum->id);
                    if($result == 1){

                        $this->logger->info('redis中存在：', [count($paymentData)]);
                        continue;
                    }
                    //判断redis中是否有这个Key

                    $pay_time = $paymentDatum->pay_time;
                    $amount = $paymentDatum->amount;
                    $this->logger->info('当前订单ID为：'.$paymentDatum->id);
                    $this->logger->info('当前订单日期为：'.$pay_time);
//                    $this->logger->info('获取此订单的日期和时间：'.$pay_time);
                    $date = date("Y-m-d",strtotime($pay_time));
                    $hour = date("H",strtotime($pay_time));
//                    $this->logger->info('获取此订单的日期为：'.$date);
//                    $this->logger->info('获取此订单的小时为：'.$hour);

                    if(empty($paymentDatum->applet_id)){
                        continue;
                    }

                    $insertData = [];
                    //获取此订单的日期和时间
                    $spread_id = $paymentDatum->spread_id;
//                    //已支付
                    if ($paymentDatum->status == 2) {

                        $firstCount = Payment::query()->where([
                            'spread_id' => $spread_id,
                            'status' => 2,
                            'applet_id' => $paymentDatum->applet_id,
                            'user_id' => $paymentDatum->user_id,
                        ])->where('id','!=',$paymentDatum->id)->where('pay_time','<=',$paymentDatum->pay_time)
                            ->count('id');
                        $is_save = false;

                        if(empty($firstCount)){
                            $paymentDatum->first_recharge = 'Y';
                            $is_save= true;
                        }
                        //先查询这个用户染色时间是否为今天
                        $userInfo = Db::table('data_user_'.$paymentDatum->applet_id)
                            ->select('id')
                            ->where('id',$paymentDatum->user_id)
                            ->where('dyeing_time','>=',$startUserDate)
                            ->where('dyeing_time','<=',$endDUserate)
                            ->first();
                        if(!empty($userInfo)){
                            $todayfirstCount = Payment::query()->where([
                                'spread_id' => $spread_id,
                                'status' => 2,
                                'applet_id' => $paymentDatum->applet_id,
                                'user_id' => $paymentDatum->user_id,
                            ])->where('id','!=',$paymentDatum->id)
                                ->where('pay_time','>=',$startUserDate)
                                ->where('pay_time','<=',$paymentDatum->pay_time)
                                ->count('id');

                            if(empty($todayfirstCount)){
                                $paymentDatum->today_first_recharge = 'Y';
                                $is_save= true;
                            }else{
                                $paymentDatum->today_after_recharge = 'Y';
                                $is_save= true;
                            }
                        }
                        if($is_save){

                            $paymentDatum->save();
                        }
                        $redis->sAdd($paymentIDKey,$paymentDatum->id);
                        $select_payment_id = $paymentDatum->id;
                    }
                }
                $redis->set($payKey,$select_payment_id);
            } else{
                $this->logger->info('没有订单需要处理');
            }
            $redis->del($orderKey);

        }catch (\Exception $e){
            $redis->del($orderKey);
            $this->logger->error('请求订单|错误：' . $e->getLine() . '|' . $e->getMessage());
        }
        $this->logger->info(date('Y-m-d H:i:s') . '------------------------结束定时获取订单数据');
    }


    public function countOrder($statisData,$arrName,$spread_id,$playlet_id,$ad_id,$applet_id){

        $keyName = $spread_id.'_'.$playlet_id.'_'.$ad_id.'_'.$applet_id;

        if (!empty($statisData[$keyName][$arrName])) {
            $statisData[$keyName][$arrName] += 1;
        } else {
            $statisData[$keyName][$arrName] = 1;
        }
        return $statisData;
    }
    public function countOrderAmount($statisData,$arrName,$spread_id,$playlet_id,$ad_id,$applet_id,$amonut){

        $keyName = $spread_id.'_'.$playlet_id.'_'.$ad_id.'_'.$applet_id;

        if (!empty($statisData[$keyName][$arrName])) {
            $statisData[$keyName][$arrName] += $amonut;
        } else {
            $statisData[$keyName][$arrName] = $amonut;
        }
        return $statisData;
    }
}